<?php
/**
 * @author Valery
 */
class Lemar_Shop
{

//----------------------------------------------------------------------------------------------------

	public static function getItemsInCart()
    {
    	$orders = Lemar_Shop::getUserOrders();
    	$itemCount = 0;
    	if (isset($orders[0]))
    	$itemCount += models_OrderMapper::getItemsCount($orders[0]->id);
//    	foreach ($orders as $order)
//    	{
//    		$itemCount += models_OrderMapper::getItemsCount($order->id);
//    	}
    	return $itemCount;
    }

//----------------------------------------------------------------------------------------------------

	public static function getTotalAmount()
    {
    	$orders = Lemar_Shop::getUserOrders();
    	$amount = 0;
    	foreach ($orders as $order)
    	{
    		$items = models_OrderMapper::getItems($order->id);
    		foreach ($items as $item)
    		{
    			$amount += $item->price * $item->quantity;
    		}
    		if (count($items) > 0)
    		{
    			$amount += $order->delivery_cost;
    		}
    	}
    	return $amount;
    }

//----------------------------------------------------------------------------------------------------

	public static function checkout($values)
    {
    	$values['status'] = 'new';
    	$orders = Lemar_Shop::getUserOrders();
    	$body = '';
    	$displayValue = 0;
    	foreach ($orders as $order)
    	{
    		$values['total_amount'] = 0;
    		$values['added'] = Lemar_Date::getCurrentDate(Lemar_Date::MYSQL_DATETIME);
    		$items = models_OrderMapper::getItems($order->id);
    		$restaurant = models_RestaurantsMapper::findById($order->idRestaurant);
    		$values['delivery_cost'] = $restaurant->deliveryCost;
    		if (array_key_exists('coupon_code_id', $values))
    		{
    			$values['delivery_cost'] = 0;
    		}
    		foreach ($items as $item)
    		{
    			$values['total_amount'] += $item->price * $item->quantity;
    		}
    		if (count($items) > 0)
    		{
    			$displayValue += $values['total_amount'] + $values['delivery_cost'];
    			models_OrderMapper::update($order->id, $values, models_OrderMapper::$_dbTable);
    		}
    		else
    		{
    			models_OrderMapper::deleteFromBase($order->id, 'models_DbTable_Order');
    		}
    		$body .= 'http://'.$_SERVER["HTTP_HOST"].'/adminarea/vieworder/id/'.$order->id."\n";
    	}
    	$email = 'admin@' . $_SERVER["HTTP_HOST"];
    	$body = 'New orders added. Check it in admin area:'."\n" . $body;
   		self::send($body , $email, $email, $email, "New order");
		return $displayValue;
    }

//----------------------------------------------------------------------------------------------------

	/**
	 * Send mail
	 *
	 * @param string $sBody - message text body
	 * @param string $sToAddress - address to
	 * @param string $sToName - name to
	 * @param string $sFromAddress - address from
	 * @param string $sFromName - name from
	 * @param string $sSubject - subject
	 *
	 * @return bool
	 */
	public static function send($sBody, $sToAddress, $sToName, $sFromAddress, $sSubject)
	{
		/* @todo use SMTP server */
		$oMail = new Zend_Mail();
//		$oMail->setBodyText($sBody);
		$oMail->setFrom($sFromAddress);
		$oMail->addTo($sToAddress, $sToName);
		$oMail->setSubject($sSubject);
		$oMail->setBodyHtml(nl2br($sBody));

		if($oMail->send())
		{
			return true;
		}
		else
		{
			Lemar_Logger::log('Lemar_Mailer::send: error  Zend_Mail->send() ', $iPriority = Zend_Log::ERR);
		}
		return false;
	}

//----------------------------------------------------------------------------------------------------

	public static function attachOrders($idUser)
    {
    	$orders = Lemar_Shop::getGuestOrders();

    	foreach ($orders as $order)
    	{
    		models_OrderMapper::update($order->id, array('user_id' => $idUser), 'models_DbTable_Order');
    	}

    	Lemar_Shop::flushGuestOrders();
    	return $itemCount;
    }

//----------------------------------------------------------------------------------------------------

	public static function getGuestOrders()
    {
     	$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
    	if (!isset($oZendSession->orders))
    	{
    		$oZendSession->orders = serialize(array());
    	}
    	$orderIds = @unserialize($oZendSession->orders);
    	if (!is_array($orderIds))
    	{
    		$orderIds = array();
    	}
    	$orderIds = array_unique($orderIds);
    	$orders = $orderIdsFiltered = array();
    	foreach ($orderIds as $id)
    	{
    		$order = models_OrderMapper::findById($id);
    		if (null != $order && '' == $order->status)
    		{
    			$orders[] = $order;
    			$orderIdsFiltered[] = $id;
    		}
    	}
    	$oZendSession->orders = serialize($orderIdsFiltered);
    	return $orders;
    }

//----------------------------------------------------------------------------------------------------

	public static function flushGuestOrders()
    {
     	$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
    	$oZendSession->orders = serialize(array());
    }

//----------------------------------------------------------------------------------------------------

	public static function getUserOrders()
    {
    	return true;
    	
    	if (Lemar_User::isLogged())
    	{
    		$idUser = Lemar_User::getLoggedUserId();
    		return models_OrderMapper::getFromCurrentCart($idUser);
    	}
    	else
    	{
    		return Lemar_Shop::getGuestOrders();
    	}
    }

//----------------------------------------------------------------------------------------------------

    public static function saveResources($idOrderItem, $params)
    {
    	foreach ($params['type'] as $key=>$type)
		{
			$x = (int)$params['x'][$key];
			$y = (int)$params['y'][$key];
			$width = (int)$params['width'][$key];
			$height = (int)$params['height'][$key];

			$data = array();

			if ('image' == $type)
			{
				$data['src'] = $params['src'][$key];
			}
			elseif ('background' == $type)
			{
				$data['src'] = $params['src'][$key];
			}
			elseif ('text' == $type)
			{
				$data['text'] = $params['text'][$key];
				$data['align'] = $params['align'][$key];
				$data['strikethrough'] = $params['strikethrough'][$key];
				$data['underline'] = $params['underline'][$key];
				$data['italic'] = $params['italic'][$key];
				$data['bold'] = $params['bold'][$key];
				$data['color'] = $params['color'][$key];
				$data['fontsize'] = ($params['fontsizecustom'][$key]?$params['fontsizecustom'][$key]:$params['fontsize'][$key]);
				$data['font'] = $params['font'][$key];
			}

			models_OrderItemResourceMapper::save(
				array(
					'order_item_id' => $idOrderItem,
					'resource' => serialize($data),
					'x' => $x,
					'y' => $y,
					'height' => $height,
					'width' => $width,
					'resource_type' => $type
				)
			);
		}
    }

//----------------------------------------------------------------------------------------------------

	public static function addToCart($idOrder = null, $idItem, $size, $quantity = 1)
    {
	    try
		{
			if (! $idOrder)
			{
				$idUser	= Lemar_User::getLoggedUserId();
				$aData 	= array(	'user_id' => $idUser,
									'status'  => $new,
				);
				$idOrder = models_OrderMapper::save($aData);

			}
			$item 	= models_CardMapper::findById($idItem);
			$aData2	= array(	'order_id' 	=> $idOrder,
								'card_id'  	=> $idItem,
								'quantity'	=> $quantity,
								'price'		=> $item->price,
								'size'		=> $size,
								'image'		=> $item->image,
			);
			$result = models_OrderItemMapper::save($aData2);
		}
		catch (Lemar_InputInvalidException $e)
		{
			$result = null;
		}
		return $result;
    }

//----------------------------------------------------------------------------------------------------

	public static function updateCartItemQuantity($idItem, $quantity)
    {
	    try
		{
			$orderMenuItem = models_OrderItemMapper::findById($idItem);
			if (null == $orderMenuItem) return false;

			$orders = Lemar_Shop::getUserOrders();

			$result = false;

			foreach ($orders as $order)
			{
				if ($order->id == $orderMenuItem->idOrder)
				{
					$result = true;
					break;
				}
			}

			if (!$result) return false;

			$result = false;

			$cou = models_OrderItemMapper::update($idItem, array('quantity' => $quantity),
				models_OrderItemMapper::$_dbTable);

//				echo $cou; die;
			$result = true;

		}
		catch (Exception $e)
		{
			$result = false;
		}
		return $result;
    }

//----------------------------------------------------------------------------------------------------

	public static function removeFromCart($idItem)
    {
	    try
		{
			$orderMenuItem = models_OrderItemMapper::findById($idItem);

			if (null == $orderMenuItem) return false;

			$orders = Lemar_Shop::getUserOrders();

			$result = false;

			foreach ($orders as $order)
			{
				if ($order->id == $orderMenuItem->idOrder)
				{
					$result = true;
					break;
				}
			}

			if (!$result) return false;

			$result = false;

//			models_OrdermenuoptionMapper::deleteByOrderMenuItemId($idItem);

			models_OrderItemMapper::deleteFromBase($idItem, models_OrderItemMapper::$_dbTable);

			$result = true;

		}
		catch (Exception $e)
		{
			$result = false;
		}
		return $result;
    }

//----------------------------------------------------------------------------------------------------

	public static function addItem($idOrder, $idMenuitem, $idMenuprice, $options, $quantity)
    {
    	$orderMenuItem = new models_Ordermenuitems();
    	$orderMenuItem->idOrder = $idOrder;
    	$orderMenuItem->idMenuItem = $idMenuitem;
    	$orderMenuItem->idMenuPrice = $idMenuprice;
    	$orderMenuItem->quantity = $quantity;

    	$aOrderMenuItem = array(
    		'order_id' => $orderMenuItem->idOrder,
    		'menu_item_id' => $orderMenuItem->idMenuItem,
    		'menu_price_id' => $orderMenuItem->idMenuPrice,
    		'quantity' => $orderMenuItem->quantity
    	);

		$orderMenuItem->id = models_OrdermenuitemsMapper::save($aOrderMenuItem);

		foreach ($options as $idMenuOption)
		{
			$orderMenuOption = new models_Ordermenuoption();
			$orderMenuOption->idOrder = $idOrder;
			$orderMenuOption->idMenuItem = $idMenuitem;
			$orderMenuOption->idMenuOption = $idMenuOption;
			$orderMenuOption->idOrderMenuItem = $orderMenuItem->id;

			$aOrderMenuOption = array(
				'order_id' => $orderMenuOption->idOrder,
				'menu_item_id' => $orderMenuOption->idMenuItem,
				'menu_option_id' => $orderMenuOption->idMenuOption,
				'order_menu_item_id' => $orderMenuOption->idOrderMenuItem
			);

			models_OrdermenuoptionMapper::save($aOrderMenuOption);
		}

		$price = models_OrdermenuitemsMapper::calculatePriceById($orderMenuItem->id);
		$aOrderMenuItem['price'] = $price;
		models_OrdermenuitemsMapper::update($orderMenuItem->id, $aOrderMenuItem, 'models_DbTable_Ordermenuitems');
    }

//----------------------------------------------------------------------------------------------------

	public static function createOrder($idRestaurant)
    {
    	$order = new models_Order();
    	$order->idRestaurant = $idRestaurant;
    	$order->added = Lemar_Date::getCurrentDate(Lemar_Date::MYSQL_DATETIME);
		$order->idRestaurant = $idRestaurant;

		if (Lemar_User::isLogged())
		{
			$order->idUser = Lemar_User::getLoggedUserId();
		}

    	$aOrder = array(
    		'restaurant_id' => $order->idRestaurant,
    		'added' => $order->added,
    		'user_id' => $order->idUser,
    	);

    	$order->id = models_OrderMapper::save($aOrder);

   		if (!Lemar_User::isLogged())
    	{
    		$oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
    		if (!isset($oZendSession->orders))
    		{
    			$oZendSession->orders = serialize(array());
    		}
    		$orderIds = unserialize($oZendSession->orders);
    		$orderIds = array_merge($orderIds, array($order->id));
    		$orderIds = array_unique($orderIds);
    		$oZendSession->orders = serialize($orderIds);
    	}

    	return $order;
    }

//----------------------------------------------------------------------------------------------------

	public static function checkCoupon($couponCode, $idUser)
    {
    	$coupon = models_CouponcodesMapper::findByCode($couponCode);

		if (null == $coupon) return false;

		$usedByUser = models_OrderMapper::getCouponcodeUseNumber($coupon->id, $idUser);

		if ($usedByUser) return false;

		$useNumber = models_OrderMapper::getCouponcodeUseNumber($coupon->id);

		if ($coupon->useNumber <= $useNumber) return false;

		return true;
    }

//----------------------------------------------------------------------------------------------------

}